
package com.example.sistemacompras;

import com.example.sistemacompras.db.DatabaseHandler;
import com.example.sistemacompras.entity.Client;
import com.example.sistemacompras.utils.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UserOperationsActivity extends Activity {
    private int mId;

    private Client mClient;

    private EditText nomeDeUsuarioU;

    private EditText EmailU;

    private Bitmap fotoU = null;

    private ImageView fotoIV = null;

    private Uri fileUri = null;

    private static final int CAPTURE_IMAGE_ACTIVITY_REQ = 0;

    private EditText passwordU;

    private String mCurrentPhotoPath;

    private DatabaseHandler db;

    private boolean mIsExcluded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_operations);
        if (db == null) {
            db = new DatabaseHandler(getApplicationContext());
        }
        nomeDeUsuarioU = (EditText) findViewById(R.id.nome_up_edit);
        nomeDeUsuarioU.setText("");
        EmailU = (EditText) findViewById(R.id.email_up_edit);
        EmailU.setText("");
        passwordU = (EditText) findViewById(R.id.password_up_edit);
        passwordU.setText("");

        fotoIV = (ImageView) findViewById(R.id.user_up_photo);
        fotoIV.setImageDrawable(getResources().getDrawable(R.drawable.images));

        fotoU = ((BitmapDrawable) ((ImageView) findViewById(R.id.user_up_photo)).getDrawable())
                .getBitmap();
        mCurrentPhotoPath = null;
        mId = getIntent().getExtras().getInt("user_id");

        mClient = db.getClientById(mId);

        nomeDeUsuarioU.setText(mClient.getName());
        EmailU.setText(mClient.getEmail());
        fotoU = mClient.getPhoto();
        passwordU.setText(mClient.getPassword());

        ((ImageView) findViewById(R.id.user_up_photo)).setImageBitmap(fotoU);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    }

    public void atualizarUsuario(View view) {
        String nomeP = nomeDeUsuarioU.getText().toString();
        String emailP = EmailU.getText().toString();
        String passwordP = passwordU.getText().toString();
        Client person = new Client();
        person.setId(mId);
        person.setEmail(emailP);
        person.setName(nomeP);
        person.setPassword(passwordP);
        if (fotoIV != null) {
            Utils util = new Utils(this);
            int proportion = 6;
            int width = util.getWidthInPixels() / proportion;
            int height = util.getHeightInPixels() / proportion;
            fotoU = getResizedBitmap((Bitmap) ((BitmapDrawable) fotoIV.getDrawable()).getBitmap(),
                    width, height);

            person.setPhoto(fotoU);
        }

        db.updateClient(person);
        Intent intent = new Intent(this, UserProfileActivity.class);
        intent.putExtra("user_id", mId);
        startActivity(intent);

        finish();
    }

    public void excluirUsuario(View view) {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Closing Activity")
                .setMessage("Are you sure you want to close this activity?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        db.deleteClient(mClient);
                        finish();
                        mIsExcluded = true;
                        UserOperationsActivity.this.finishOperationsActivity();

                    }

                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).show();

    }

    static final int REQUEST_TAKE_PHOTO = 1;

    @SuppressLint("SimpleDateFormat")
    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );
        try {
            mCurrentPhotoPath = getPath(this, Uri.parse(image.toURI().toString()));

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        return image;
    }

    public void shootPhoto(View view) {
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = Uri.fromFile(getOutputPhotoFile());
        i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQ);
    }

    private File getOutputPhotoFile() {
        File directory = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                getPackageName());
        if (!directory.exists()) {
            if (!directory.mkdirs()) {

                return null;
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(0));
        return new File(directory.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQ) {
            if (resultCode == RESULT_OK) {
                Uri photoUri = null;
                if (data == null) {
                    Toast.makeText(this, "Image saved successfully", Toast.LENGTH_LONG).show();
                    photoUri = fileUri;
                } else {
                    photoUri = data.getData();
                    Toast.makeText(this, "Image saved successfully in: " + data.getData(),
                            Toast.LENGTH_LONG).show();
                }
                showPhoto(photoUri);
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Callout for image capture failed!", Toast.LENGTH_LONG).show();
            }
        }
        // if (data != null) {
        // Log.wtf("TESTE", "Caiu no operations");
        // Intent returnIntent = new Intent();
        // returnIntent.putExtra("excluido", true);
        // setResult(RESULT_OK, returnIntent);
        // }
    }

    private void showPhoto(Uri photoUri) {

        File imageFile = new File(photoUri.getEncodedPath());
        if (imageFile.exists()) {
            Drawable oldDrawable = fotoIV.getDrawable();
            Utils util = new Utils(this);
            int proportion = 6;
            int width = util.getWidthInPixels() / proportion;
            int height = util.getHeightInPixels() / proportion;
            fotoU = getResizedBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()), width,
                    height);
            if (oldDrawable != null) {
                ((BitmapDrawable) oldDrawable).getBitmap().recycle();
            }
            BitmapDrawable drawable = new BitmapDrawable(this.getResources(), fotoU);
            fotoIV.setScaleType(ImageView.ScaleType.FIT_CENTER);
            fotoIV.setImageDrawable(drawable);

        }
    }

    public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

        int width = bm.getWidth();

        int height = bm.getHeight();

        float scaleWidth = ((float) newWidth) / width;

        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();

        matrix.postScale(scaleWidth, scaleHeight);
        matrix.postRotate(90.0f);

        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

        return resizedBitmap;

    }

    public static String getPath(Context context, Uri uri) throws URISyntaxException {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {
                "_data"
            };
            Cursor cursor = null;

            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public void finishOperationsActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra("excluded", mIsExcluded);
        startActivity(intent);
        finish();
    }
}
